package com.forum.post.service.impl;

import com.forum.model.entity.Post;
import com.forum.post.client.AutoAuditClient;
import com.forum.post.config.AutoAuditConfig;
import com.forum.post.dto.AuditFeedbackDTO;
import com.forum.post.dto.AuditRequestDTO;
import com.forum.post.dto.AuditResultDTO;
import com.forum.post.mapper.PostCategoryMapper;
import com.forum.post.mapper.SensitiveWordMapper;
import com.forum.post.model.entity.PostCategory;
import com.forum.post.model.entity.SensitiveWord;
import com.forum.post.service.AutoAuditService;
import com.forum.post.service.TagService;

import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class AutoAuditServiceImpl implements AutoAuditService {
    
    @Autowired
    private AutoAuditClient autoAuditClient;
    
    @Autowired(required = false)
    private PostCategoryMapper categoryMapper;
    
    @Autowired
    private SensitiveWordMapper sensitiveWordMapper;
    
    @Autowired(required = false)
    private TagService tagService;
    
    @Autowired
    private AutoAuditConfig auditConfig;
    
//    @PostConstruct
//    public void init() {
//        if (auditConfig.getSensitiveWord().isAutoInit()) {
//            initSensitiveWords();
//        }
//    }
    
    @Override
    public AuditResultDTO auditPost(Post post) {
        if (!auditConfig.isEnabled()) {
            // 自动审核未启用，返回需要人工审核的结果
            return createDefaultReviewResult(post.getId());
        }
        
        try {
            // 准备审核请求
            AuditRequestDTO request = prepareAuditRequest(post);
            
            // 调用审核服务
            AuditResultDTO result = autoAuditClient.auditContent(request);
            
            log.info("帖子 {} 审核结果: {}, 置信度: {}", 
                    post.getId(), result.getAuditResult(), result.getConfidence());
            
            return result;
        } catch (Exception e) {
            log.error("帖子审核失败: {}", e.getMessage(), e);
            return createDefaultReviewResult(post.getId());
        }
    }
    
    @Override
    public void submitFeedback(Long postId, Long adminId, String aiDecision, 
                                String finalDecision, boolean isCorrect, String feedback) {
        try {
            AuditFeedbackDTO feedbackDTO = AuditFeedbackDTO.builder()
                .postId(postId)
                .adminId(adminId)
                .aiDecision(aiDecision)
                .finalDecision(finalDecision)
                .isCorrect(isCorrect)
                .feedback(feedback)
                .build();
                
            autoAuditClient.submitFeedback(feedbackDTO);
            log.info("提交审核反馈成功：帖子ID={}, 管理员ID={}", postId, adminId);
        } catch (Exception e) {
            log.error("提交审核反馈失败: {}", e.getMessage(), e);
        }
    }
    
//    @Override
//    public void initSensitiveWords() {
//        try {
//            log.info("初始化敏感词库...");
//
//            // 读取敏感词文件
//            ClassPathResource resource = new ClassPathResource(auditConfig.getSensitiveWord().getInitFilePath());
//            List<String> words = new ArrayList<>();
//
//            try (BufferedReader reader = new BufferedReader(
//                    new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8))) {
//                words = reader.lines()
//                        .map(String::trim)
//                        .filter(line -> !line.isEmpty())
//                        .collect(Collectors.toList());
//            } catch (IOException e) {
//                log.error("读取敏感词文件失败: {}", e.getMessage(), e);
//                return;
//            }
//
//            if (words.isEmpty()) {
//                log.warn("敏感词文件为空");
//                return;
//            }
//
//            // 构建敏感词实体
//            List<SensitiveWord> sensitiveWords = new ArrayList<>();
//            for (String word : words) {
//                SensitiveWord sensitiveWord = new SensitiveWord();
//                sensitiveWord.setWord(word);
//                sensitiveWord.setCategory("默认");
//                sensitiveWord.setLevel(2); // 中等级别
//                sensitiveWord.setStatus(1); // 启用
//                sensitiveWords.add(sensitiveWord);
//            }
//
//            // 批量插入敏感词
//            int count = sensitiveWordMapper.batchInsert(sensitiveWords);
//            log.info("成功导入 {} 个敏感词", count);
//
//        } catch (Exception e) {
//            log.error("初始化敏感词库失败: {}", e.getMessage(), e);
//        }
//    }
    
    private AuditRequestDTO prepareAuditRequest(Post post) {
        AuditRequestDTO request = new AuditRequestDTO();
        request.setPostId(post.getId());
        request.setTitle(post.getTitle());
        request.setContent(post.getContent());
        request.setUserId(post.getUserId());
        
        // 设置分类名称 - 添加try-catch保护数据库查询操作
        if (categoryMapper != null && post.getCategoryId() != null) {
            try {
                PostCategory category = categoryMapper.selectById(post.getCategoryId());
                if (category != null) {
                    request.setCategory(category.getName());
                }
            } catch (Exception e) {
                log.warn("获取帖子分类信息失败: {}, 将使用默认分类", e.getMessage());
                // 设置一个默认分类或使用已有的分类名
                if (post.getCategoryName() != null) {
                    request.setCategory(post.getCategoryName());
                } else {
                    request.setCategory("默认分类");
                }
            }
        } else if (post.getCategoryName() != null) {
            // 如果已经有categoryName，直接使用
            request.setCategory(post.getCategoryName());
        }
        
        // 获取标签列表
        List<String> tags = Collections.emptyList();
        if (tagService != null) {
            try {
                tags = tagService.getTagNamesByPostId(post.getId());
            } catch (Exception e) {
                log.warn("获取帖子标签失败: {}", e.getMessage());
            }
        }
        request.setTags(tags);
        
        return request;
    }
    
    private AuditResultDTO createDefaultReviewResult(Long postId) {
        return AuditResultDTO.builder()
                .postId(postId)
                .auditResult("REVIEW")
                .confidence(0.5)
                .reasons(Collections.singletonList("系统配置为人工审核"))
                .suggestion("请管理员进行人工审核")
                .build();
    }
} 